import java.util.Base64;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

public class ImageString {
    static Base64.Encoder encoder = Base64.getEncoder();
    static Base64.Decoder decoder = Base64.getDecoder();

    public static void main(String[] args) {

    }

    public static String getImageBinary(String imagePath) throws IOException {
        try {
            BufferedImage image = ImageIO.read(new File(imagePath));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "png", baos);
            byte[] bytes = baos.toByteArray();
            return encoder.encodeToString(bytes).trim();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void base64StringToImage(String base64String, String outputImagePath) throws IOException {
//        byte[] png_nm = {(byte)0x89, (byte)0x50, (byte)0x4E, (byte)0x47, (byte)0x0D, (byte)0x0A, (byte)0x1A, (byte)0x0A};
//        byte[] result;
        try {
            byte[] bytes = decoder.decode(base64String);
//            result = concatenate(png_nm, bytes);

            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            BufferedImage bufferedImage = ImageIO.read(bais);
            File outputFile = new File(outputImagePath);
            ImageIO.write(bufferedImage, "png", outputFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static byte[] concatenate(byte[] first, byte[] second) {
        byte[] result = new byte[first.length + second.length];

        // 复制第一个数组
        System.arraycopy(first, 0, result, 0, first.length);

        // 复制第二个数组到结果数组的剩余部分
        System.arraycopy(second, 0, result, first.length, second.length);

        return result;
    }

    public static byte[] readFileToByteArray(String filePath) {
        byte[] fileBytes = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            fileBytes = new byte[(int) file.length()];
            fis.read(fileBytes);
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileBytes;
    }
}
